<template>
  <!-- 收款添加 -->
  <div class="contractInfo box">
    <el-divider content-position="left">{{
      $route.query.mode == "add" ? "添加收款" : "编辑收款"
    }}</el-divider>
    <div class="formBox">
      <el-form
        :model="form"
        :rules="rules"
        ref="addForm"
        label-width="auto"
        label-position="right"
      >
        <el-form-item label="收款名称" prop="paymentName">
          <el-input
            v-model="form.paymentName"
            clearable
            placeholder="请输入收款名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="paymentType">
          <el-select
            v-model="form.paymentType"
            placeholder="请选择"
            style="width: 100%"
            clearable
            @change="paymentTypeChange"
          >
            <el-option
              v-for="item in paymentTypeList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="客户"
          prop="contractId"
          class="formRow"
          v-if="form.paymentType == 3"
        >
          <sc-table-select
            v-model="form.customerData"
            :apiObj="customerApiObj"
            style="width: 100%"
            table-width="100%"
            clearable
            collapse-tags
            collapse-tags-tooltip
            @change="customerChange"
            :props="customerProps"
            :params="customerSearchForm"
          >
            <template #header="{ form, submit }">
              <el-form :model="customerSearchForm">
                <el-row :gutter="20">
                  <el-col :span="20">
                    <el-input
                      v-model="customerSearchForm.search"
                      placeholder="客户名称"
                      clearable
                      style="width: 100%"
                    ></el-input>
                  </el-col>
                  <!-- <el-col :span="6">
                    <el-date-picker
                      v-model="customerSearchForm.startTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="开始时间"
                      :teleported="false"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-col>
                  <el-col :span="6">
                    <el-date-picker
                      v-model="customerSearchForm.endTime"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="开始时间"
                      :teleported="false"
                      style="width: 100%"
                    ></el-date-picker>
                  </el-col> -->
                  <el-col :span="4">
                    <el-form-item width="100%">
                      <el-button type="primary" @click="submit">查询</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </template>
            <el-table-column
              label="客户名称"
              prop="customerName"
              min-width="150"
            ></el-table-column>
            <!-- <el-table-column label="应收金额" prop="contractMoney" width="150">
            </el-table-column>
            <el-table-column
              label="实收金额"
              prop="actualMoney"
              width="200"
            ></el-table-column> -->
          </sc-table-select>
          <el-button type="primary" @click="toEditCustomer">详情</el-button>
        </el-form-item>
        <el-form-item
          label="源单记录"
          style="width: 100%"
          v-if="form.paymentType == 3"
        >
          <source-record
            ref="sourceRecord"
            :customerId="form.customerId"
            @setTotalMoney="setTotalMoney"
          ></source-record>
        </el-form-item>

        <el-form-item label="收款金额" prop="money" class="priceItem">
          <el-input
            v-model="form.money"
            clearable
            placeholder="请输入收款金额"
            oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
            @blur="form.money = $event.target.value"
            @input="changeMoney"
            :disabled="form.paymentType == 3"
          >
            <template #append>元</template>
          </el-input>
          <!-- <div class="el-form-item-msg" v-if="form.paymentType == 3">
              {{ form.customerData.customerName }}欠款：{{
                form.arrearsMoney ?? 0
              }}元
            </div> -->
        </el-form-item>
        <el-form-item label="收款方式" prop="repaymentType">
          <el-select
            v-model="form.repaymentType"
            placeholder="请选择收款方式"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in repaymentTypeOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="收款账号" prop="account">
          <el-input
            v-model="form.account"
            clearable
            placeholder="请输入收款账号"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="收款日期" prop="repaymentTime">
          <el-date-picker
            v-model="form.repaymentTime"
            type="date"
            placeholder="请选择收款日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width: 100%">
          <el-input
            v-model="form.remark"
            clearable
            type="textarea"
            rows="3"
            placeholder="请输入备注内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <sc-upload-file
            v-model="form.otherFileList"
            :limit="10"
            :multiple="false"
            tip="最多上传10个文件,单个文件不要超过20M"
          >
            <el-button type="primary" plain icon="el-icon-upload"
              >上传附件</el-button
            >
          </sc-upload-file>
        </el-form-item>
      </el-form>

      <!-- 审核流程项 -->
      <!-- <check-form-item
        ref="checkFormItem"
        @setCheckConfig="setCheckConfig"
        :field="this.form"
        :checkType="checkType"
        v-if="$route.query.mode == 'add'"
      ></check-form-item> -->

      <div class="button">
        <el-button type="primary" @click="save" :loading="isSaveing"
          >保 存</el-button
        >
        <el-button @click="cencel">取 消</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { queryTypeByDic } from '@/utils/getData'
import checkFormItem from '@/components/checkProcess/checkFormItem.vue'
import sourceRecord from './components/sourceRecord.vue'
export default {
  name: 'collectAdd',
  components: {
    sourceRecord
  },
  data () {
    return {
      checkType: 5,//工作流的类型
      isSaveing: false,
      selectCustomerLoading: false,
      selectContractLoading: false,
      selectLoading: false,
      //表单数据
      form: {
        adminId: '',//跟进人id --登录时id
        departmentId: '',
        customerId: '',
        repaymentNum: '',//收款编号
        paymentName: '',//收款名称
        planId: 0,//收款计划id
        money: '',//收款金额
        paymentType: 3,//收款类型
        repaymentType: 1,//收款方式
        account: '',//收款账号
        repaymentTime: '',//收款时间
        otherFileList: [],//附件
        remark: '',//备注
        exempt: '',//是否免审
        workflowJsonList: [],
        customerData: {},//客户数据
        arrearsMoney: null,//客户欠款
        customerPaymentContractList: []//收款记录
      },
      paymentTypeList: [{ name: '客户', value: 3 }, { name: '其他', value: 2 }],
      repaymentTypeOptions: [],//收款方式
      customerSearchForm: {
        search: '',
        startTime: '',
        endTime: ''
      },
      customerApiObj: this.$API.finance.collectManagement.getNotCollectionList,
      customerProps: {
        label: 'customerName',
        value: 'customerId',
      },
      monthList: [{ name: '1月', value: '01' }, { name: '2月', value: '02' }, { name: '3月', value: '03' }, { name: '4月', value: '04' }, { name: '5月', value: '06' }, { name: '7月', value: '07' }, { name: '8月', value: '08' }, { name: '9月', value: '09' }, { name: '10月', value: '10' },
      { name: '11月', value: '11' }, { name: '12月', value: '12' }],
      contractList: [],//合同列表
      //验证规则
      rules: {
        paymentName: [
          { required: true, message: '请输入收款名称' }
        ],
        customerData: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        money: [
          { required: true, message: '请输入收款金额' }
        ],
        paymentType: [
          { required: true, message: '请选择收款类型', trigger: 'change' }
        ],
        repaymentTime: [
          { type: 'date', required: true, message: '请选择收款日期', trigger: 'change' }
        ],
        repaymentType: [
          { required: true, message: '请选择收款方式', trigger: 'change' }
        ],
        account: [
          { required: true, message: '请输入收款账号' }
        ],
        userId: [
          { required: true, message: '请选择项目负责人', trigger: 'change' }
        ],
      }
    }
  },
  components: {
    checkFormItem,
    sourceRecord
  },
  mounted () {
    this.getType()
    if (this.$route.query.mode == 'edit') {
      this.getCollectById()
    }
  },
  methods: {
    // 客户数据
    customerChange (val) {
      console.log(val)
      this.form.customerId = val.id
      // this.form.arrearsMoney = val.contractMoney - val.actualMoney
      // this.form.money = this.form.arrearsMoney
      this.form.paymentName = val.customerName + '-的收款'
    },

    toEditCustomer () {
      if (!this.form.customerData.id) {
        this.$message.error("请选择客户")
        return
      }
      this.$router.push({
        path: "/contract/customerManagement/customerDetail",
        query: {
          id: this.form.customerData.id,

        },
      })
    },
    // 获取收款支付类型
    async getType () {
      this.repaymentTypeOptions = await queryTypeByDic('payment')
    },
    // 选择类型
    paymentTypeChange () {
      this.form.money = ' '
      this.form.arrearsMoney = 0
      this.form.paymentName = ' '
      this.form.customerData = {}
    },

    // 审批流配置
    setCheckConfig (list, exempt) {
      this.form.workflowJsonList = list
      this.form.exempt = exempt
    },
    // 获取收款信息
    async getCollectById () {
      let { data } = await this.$API.finance.collectManagement.getCollectDetailById.post({ id: this.$route.query.id })
      this.form = data
    },

    // 金额改变
    changeMoney () {
      if (this.form.money > this.form.arrearsMoney) this.form.money = this.form.arrearsMoney
    },

    setTotalMoney (val) {
      this.form.money = val

    },

    async save () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          let userInfo = this.$TOOL.data.get('USER_INFO')
          this.form.departmentId = userInfo.departmentId
          this.form.adminId = userInfo.userId
          this.form.customerPaymentContractList = this.$refs.sourceRecord.recordList
          let fileType = ''
          this.form.otherFileList.map(item => {
            if (item.url) {
              let arr = item.url.split('.')
              let type = arr[arr.length - 1]
              // fileType  1图片 2文件
              let imageType = 'jpg/png/jpeg/svg'
              if (imageType.includes(type)) {
                fileType = 1
              } else {
                fileType = 2
              }
              item.fileType = fileType
              item.fileName = item.name
            }
          })
          this.isSaveing = true
          let res = null
          let mode = this.$route.query.mode
          if (mode == 'add') {
            res = await this.$API.finance.collectManagement.addCollect.post(this.form)
          } else if (mode == 'edit') {
            delete this.form.status
            delete this.form.createTime
            delete this.form.updateTime
            res = await this.$API.finance.collectManagement.updateCollect.post(this.form)
          }
          this.isSaveing = false
          if (res.code == 200) {
            this.$emit('success', this.form, this.mode)
            this.closeSelectedTag(this.$route)
            this.$router.push({
              path: '/finance/collectManagement'
            })
            this.$message.success("操作成功")
          }
        }
      })
    },

    // 取消客户添加
    cencel () {
      this.closeSelectedTag(this.$route)
      this.$router.push({
        path: '/finance/collectManagement'
      })
    },
    //关闭tag
    closeSelectedTag (tag) {
      this.$store.commit("removeViewTags", tag)
      this.$store.commit("removeIframeList", tag)
      this.$store.commit("removeKeepLive", tag.name)
    },
  }

}

</script>
<style lang='scss' scoped>
.box {
  margin: 10px;
}

.formBox {
  padding: 30px;
  background: #fff;
  .el-form {
    width: 100%;
  }
}
.formRow {
  :deep(.el-form-item__content) {
    flex-wrap: nowrap;
    .el-button {
      margin-left: 10px;
    }
  }
}
.button {
  margin-top: 50px;
  padding-left: 60px;
}

:deep(.el-divider__text) {
  padding: 0 10px;
  font-size: 18px;
  // font-weight: 600;
  background-color: #f6f8f9;
}

// .selectMonth .el-picker-panel {
//   color: #333;
// }

:deep(.selectMonth) {
  .el-date-picker__header,
  .el-date-picker__prev-btn,
  .el-date-picker__next-btn {
    display: none;
  }
}
</style>
